<template>
	<view class="container">
		<image class="top-bg" src="@/static/personalCenter/ic_my_top_bg.png" mode="widthFix"></image>
		<!-- <uni-nav-bar title="个人中心" statusBar :border="false" backgroundColor="transparent"></uni-nav-bar> -->
		<view v-if="!userInfoCheck" class="notLoggedIn" @click="openAuthorizedDialog">
			<image class="avatar" src="@/static/personalCenter/ic_not_logged_in.png" mode="widthFix"></image>
			<text class="nickName">点击授权登录</text>
		</view>

		<view v-else-if="userInfoCheck" class="notLoggedIn" @click="openAuthorizedDialog">
			<image class="avatar" :src="avatarUserUrl" mode="widthFix"></image>
			<text class="nickName">{{ nickName }}</text>
		</view>

		<image src="/static/personalCenter/ic_mine_ad.png" mode="widthFix" style="width: 710rpx;margin-left: 20rpx;">
		</image>

		<view class="menu-list">
			<menuItem title="我的预约" @itemClick="handleMenu" />
			<menuItem title="门店入口" @itemClick="handleMenu" />
			<menuItem title="帮助中心" @itemClick="handleMenu" />
			<menuItem title="关于我们" @itemClick="handleMenu" />
		</view>
		<!-- 	<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="authorizedDialog">
				<text class="companyName">客满</text>
				<text class="desc">请您授权头像昵称信息，您授权的信息将受到严格保护请放心使用。</text>
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="border: none;
		background: white;">
					<view v-if="!avatarUserUrl" class="unauthorized">
						<image class="avatar" src="@/static/personalCenter/ic_not_logged_in.png" mode="widthFix">
						</image>
						<text class="desc">获取头像</text>
					</view>
					<view v-else class="unauthorized">
						<image class="avatar" :src="avatarUserUrl" mode="widthFix"></image>
						<text class="desc"></text>
					</view>
				</button>
				<input name="nickName" v-model="nickName" type="nickname" class="inputNickName" placeholder="请输入昵称"
					@blur="getNickName" />

				<text class="authorizedBtn" @click="handleCheckUserInfo">确认授权</text>
			</view>

		</uni-popup> -->

		<authorizedLoginDialog ref="popup" @ok="sureLogin" />
	</view>
</template>
<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		navigateTo
	} from '@/utils/util.js'

	import {
		getUserInfo,
		updateUserInfo,
		uploadFile
	} from '@/api/index.js'
	import menuItem from './components/menuItem.vue'
	import authorizedLoginDialog from '@/components/authorizedLoginDialog.vue'
	const popup = ref()
	const nickName = ref()
	const userImageBase64 = ref("")
	const avatarUserUrl = ref()
	const userInfoCheck = ref(false)
	const handleMenu = (title) => {
		console.log(title);
		if (title == '资料管理') {
			navigateTo({
				url: `/pages/dataManagement/index`
			})
		} else if (title == '我的收藏') {
			navigateTo({
				url: `/pages/myCollection/index`
			})
		} else if (title == '我的预约') {
			uni.switchTab({
				url: `/pages/myBook/index`
			})
		}
	}
	const openAuthorizedDialog = () => {
		// popup.value.open()
	}
	const sureLogin = () => {
		popup.value.close();
		getMineUserInfo()
	}
	const onChooseAvatar = (e) => {
		const {
			avatarUrl
		} = e.detail
		// avatarUserUrl.value = avatarUrl
		uploadAvatar(avatarUrl)
	}
	const getTokenStorage = () => {
		let token = ''
		try {
			token = uni.getStorageSync('token')
		} catch (e) {}
		return token
	}
	const uploadAvatar = (filePath) => {
		// 调用uni.uploadFile方法上传头像  
		// 全局默认的头信息（方便以后扩展）
		const defaultHeader = {}

		const token = getTokenStorage()
		defaultHeader['api-token'] = token
		defaultHeader['api-name'] = 'wxapp'
		uni.uploadFile({
			url: 'https://order.weiet.com/data/api.auth.center/upload', // 替换为你的服务器接口地址  
			filePath: filePath,
			header: defaultHeader,
			name: 'file', // 根据你的服务器接口要求设置  
			formData: {
				// 如果需要，可以在这里添加其他表单数据  
			},
			success: (res) => {
				// 处理上传成功的逻辑
				const data = JSON.parse(res.data || "")
				console.log('头像上传成功:', data.code);
				if (data.code) {
					avatarUserUrl.value = data.data.url
				} else {
					uni.showToast({
						icon: "none",
						title: data.info
					})
				}
			},
			fail: (err) => {
				// 处理上传失败的逻辑  
				console.error('头像上传失败:', err);
				uni.showToast({
					icon: "none",
					title: "头像上传失败"
				})
			}
		});
	}

	const getToBase64 = (filePath) => {
		wx.downloadFile({
			url: filePath,
			success(res) {
				console.log(res, 'res')
				wx.getFileSystemManager().readFile({
					filePath: res.tempFilePath, //选择图片返回的相对路径
					encoding: 'base64', //编码格式：base64 | hex(16进制)
					success: res => { //成功的回调
						avatarUserUrl.value = filePath;
						userImageBase64.value = 'data:image/png;base64,' + res.data;
						console.log(userImageBase64.value); // 打印base64格式图片
						uploadFileBase64()
					}
				})
			}
		})
	};

	const uploadFileBase64 = async () => {
		let res = await uploadFile({
			base64: userImageBase64.value
		})
		if (res.code) {
			console.log("uploadFile=>", res.data.url);
			// avatarUserUrl.value = res.data.url
		} else {
			uni.showToast({
				icon: "none",
				title: res.info
			})
		}
	};
	const getNickName = (e) => {
		nickName.value = e.detail.value
	}

	const handleCheckUserInfo = () => {
		console.log(avatarUserUrl.value);
		console.log(nickName.value);
		const isCheck = avatarUserUrl.value && nickName.value
		if (isCheck) {
			setMineUserInfo()
			popup.value.close()
		}
	}

	const checkUserInfo = (userInfo) => {
		if (userInfo && userInfo.headimg) {
			avatarUserUrl.value = userInfo.headimg
			nickName.value = userInfo.username || userInfo.nickname
			userInfoCheck.value = true
		} else {
			userInfoCheck.value = false
		}
	}

	const getMineUserInfo = async () => {
		let res = await getUserInfo()
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			uni.setStorageSync("userInfo", res.data)
			checkUserInfo(res.data)
		}
	}


	const setMineUserInfo = async () => {
		let res = await updateUserInfo({
			headimg: avatarUserUrl.value,
			username: nickName.value,
		})
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			getMineUserInfo()
		}
	}
	onLoad(() => {
		getMineUserInfo()
	})
	onShow(() => {
		let userInfo = uni.getStorageSync('userInfo') || {};
		checkUserInfo(userInfo)
	})
</script>
<style lang="scss" scoped>
	.top-bg {
		width: 100%;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		display: block;
	}

	.menu-list {
		margin-top: 40rpx;
	}

	.notLoggedIn {
		position: relative;
		display: flex;
		padding-top: 20rpx;
		margin-bottom: 20rpx;
		flex-direction: row;
		align-items: center;

		.avatar {
			border-radius: 100%;
			overflow: hidden;
			background-color: #f5f5f5;
			margin-left: 28rpx;
			height: 99rpx;
			width: 99rpx;
		}

		.nickName {
			font-size: 34rpx;
			color: #0D0D0D;
			margin-left: 32rpx;
		}
	}

	.authorizedDialog {
		display: flex;
		flex-direction: column;
		align-items: center;

		.companyName {
			width: 690rpx;
			font-size: 48rpx;
			margin-top: 20rpx;
			font-weight: 600;
			color: #1d1d1d;
		}

		.desc {
			width: 690rpx;
			margin-top: 10rpx;
			font-size: 30rpx;
			color: #737B79;
		}


		.unauthorized {
			display: flex;
			margin-top: 40rpx;
			flex-direction: column;
			align-items: center;

			&:active {
				opacity: 0.7;
			}
		}

		.avatar {
			border-radius: 100%;
			overflow: hidden;
			background-color: #f5f5f5;
			height: 200rpx;
			width: 200rpx;
		}

		.inputNickName {
			width: 600rpx;
			margin: 20rpx auto;
			height: 68rpx;
			line-height: 68rpx;
			background: #FFFFFF;
			font-size: 32rpx;
			padding: 0 20rpx;
			border-radius: 10rpx;
			border: 2rpx solid #2462CB;
		}

		button {
			margin: 0;
			padding: 0;
			background-color: inherit;
			position: static;
		}

		button:after {
			content: none;
		}

		button::after {
			border: none;
		}

		.authorizedBtn {
			margin-top: 30rpx;
			margin-bottom: 40rpx;
			width: 640rpx;
			height: 80rpx;
			line-height: 80rpx;
			background: #2251A2;
			border-radius: 10rpx;
			font-size: 24rpx;
			text-align: center;
			color: #FFFFFF;
			font-size: 34rpx;

			&:active {
				opacity: 0.7;
			}
		}
	}
</style>